<?php

namespace App\Http\Middleware;

use App\Models\OperationLog;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

/**
 * @Class   RequestMiddleware 记录请求日志，方便开发者调试
 * @package App\Http\Middleware
 */
class RequestMiddleware
{
    /**
     * @function 设置不记录日志的url
     * @param \Illuminate\Http\Request $request
     * @return   array
     * @other    排除规则依照request()->is()方法
     */
    private function setExceptUrl($request)
    {
        return [
            'admin/logs*', 'admin/logs/*',
        ];
    }


    /**
     * @function 设置不记录响应日志的url
     * @param \Illuminate\Http\Request $request
     * @return   array
     * @other    排除规则依照request()->is()方法
     */
    private function setExceptRecordResponseDataUrl($request)
    {
        return [

        ];
    }


    /**
     * @function 设置不记录的荷载项
     * @param \Illuminate\Http\Request $request
     * @return   array
     * @other    比如防止CSRF的_token
     */
    private function setExceptPayload($request)
    {
        return [
            '_token', '_method'
        ];
    }


    /**
     * @function 设置不记录日志的请求头
     * @param \Illuminate\Http\Request $request
     * @return   array
     * @other    void
     */
    private function setExceptHeader($request)
    {
        return [
            //官方
            'accept', 'accept-encoding', 'accept-language', 'authorization',
            'access-control-allow-credentials', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-allow-origin',
            'access-control-expose-headers', 'access-control-max-age', 'access-control-request-headers', 'access-control-request-method',
            'cache-control', 'charset', 'connection', 'content-length', 'content-type_except', 'cookie',
            'host', 'origin', 'pragma', 'referer',
            'sec-ch-ua', 'sec-ch-ua-mobile', 'sec-ch-ua-platform', 'sec-fetch-dest', 'sec-fetch-mode', 'sec-fetch-site',
            'upgrade-insecure-requests', 'user-agent', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-proto', 'x-requested-with',
            //自定义
        ];
    }


    /**
     * @function 是否记录非json格式的响应的数据
     * @param \Illuminate\Http\Request $request
     * @return   bool
     * @other    void
     */
    private function isRecordNotJsonResponseData($request)
    {
        return false;
    }
//------------------------------------------------此分割线以下代码无需修改------------------------------------------------

    /**
     * @function 请求日志中间件
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request):(\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return   \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     * @other    void
     */
    public function handle(Request $request, Closure $next)
    {

        if ($this->getExceptUrl($request)) {
            return $next($request);
        }
        $request_and_response = [
            'url' => $this->getFullUrl($request),
            'path' => $request->getPathInfo(),
            'method' => $this->getRequestMethod($request),
            'ip' => $this->getClientIp($request),
            'ua' => $this->getUa($request),
            //'payload' => $this->getRequestPayload($request),
            'input' => json_encode($request->all(),  JSON_UNESCAPED_UNICODE),
            'file' => json_encode($this->getClearRequestFile($request),  JSON_UNESCAPED_UNICODE),
            'header' => json_encode($this->getClearRequestHeader($request),  JSON_UNESCAPED_UNICODE),
            'time' => 0,
            'mem' => '0B',
            'code' => 0,
            'user_id' => Auth::guard('api')->user()->id ?? 0,
            'response' => null,
        ];

        //不记录响应日志的url，存入文件
        $is_except_record_response_data_url = $this->getExceptRecordResponseDataUrl($request);
        if ($is_except_record_response_data_url) {
            Log::channel('request')->info($this->dataFormat($request_and_response));
        }

        $start = microtime(true);
        $response = $next($request);
        $end = microtime(true);

        if (!$is_except_record_response_data_url) {
            $request_and_response['time'] = bcmul(bcsub($end, $start, 6), 1000, 2);
            $request_and_response['mem'] = $this->getUsageMemory();
            $request_and_response['code'] = $this->getHttpCode($response);
            $request_and_response['response'] = $this->responseFormat($request, $response) ? json_encode($this->responseFormat($request, $response),  JSON_UNESCAPED_UNICODE) : null;

            try {
                OperationLog::create($request_and_response);
            }catch (\Exception $e){
                Log::channel('request')->info($this->dataFormat($request_and_response));
            }

        }

        return $response;
    }


    /**
     * @function 获取不记录日志的url
     * @param \Illuminate\Http\Request $request
     * @return   bool
     * @other    void
     */
    private function getExceptUrl($request)
    {
        $blacklist = array_filter($this->setExceptUrl($request));
        if (!$blacklist) {
            return false;
        }

        foreach ($blacklist as $every_blacklist) {
            if ($request->is($every_blacklist)) {
                return true;
            }
        }

        return false;
    }


    /**
     * @function 获取不记录响应日志的url
     * @param \Illuminate\Http\Request $request
     * @return   bool
     * @other    void
     */
    private function getExceptRecordResponseDataUrl($request)
    {
        $blacklist = array_filter($this->setExceptRecordResponseDataUrl($request));
        if (!$blacklist) {
            return false;
        }

        foreach ($blacklist as $every_blacklist) {
            if ($request->is($every_blacklist)) {
                return true;
            }
        }

        return false;
    }


    /**
     * @function 获取完整的请求路径
     * @param \Illuminate\Http\Request $request
     * @return   string
     * @other    void
     */
    private function getFullUrl($request)
    {
        return urldecode($request->fullUrl());
    }


    /**
     * @function 获取请求方式
     * @param \Illuminate\Http\Request $request
     * @return   string
     * @other    由于laravel存在_method覆盖机制，若有括号，则括号内的为真正的请求方式
     */
    private function getRequestMethod($request)
    {
        $real_method = $_SERVER['REQUEST_METHOD'] ?? '';

        //防止乱传参导致的错误
        try {
            $laravel_method = $request->method();
        } catch (\Exception $exception) {
            $laravel_method = $real_method;
        }

        if ($real_method === $laravel_method) {
            return $real_method;
        }

        return "{$laravel_method}({$real_method})";
    }


    /**
     * @function 获取客户端的IP
     * @param \Illuminate\Http\Request $request
     * @return   string
     * @other    void
     */
    private function getClientIp($request)
    {
        return $request->getClientIp();
    }


    /**
     * @function 获取用户代理
     * @param \Illuminate\Http\Request $request
     * @return   string
     * @other    void
     */
    private function getUa($request)
    {
        return $request->header('user-agent') ?? '""';
    }


    /**
     * @function 获取请求荷载，包含x-www-form-urlencoded、multipart/form-data、application/json、application/xml等纯文本荷载数据
     * @param \Illuminate\Http\Request $request
     * @return   array
     * @other    void
     */
    private function getRequestPayload($request)
    {
        if ($request->method() === 'GET') {
            return [];
        }
        $except = collect($request->query())->keys()->merge($this->setExceptPayload($request))->filter();
        $input = collect($request->input())->except($except)->map(function ($val) {
            if (is_null($val)) {
                return '';
            }
            return $val;
        })->toArray();

        if ($input) {
            return $input;
        }

        $raw = $request->getContent();
        //兼容application/xml、text/xml
        if (strstr($request->header('content-type'), 'xml')) {
            if (!$raw) {
                return [];
            }
            if (!$this->isXml($raw)) {
                return [$raw];
            }
            return json_decode(json_encode(simplexml_load_string(str_replace(["\r", "\n"], '', $raw))), true);
        }

        return array_filter([$raw]);
    }


    /**
     * @function 获取简洁的文件上传数据
     * @param \Illuminate\Http\Request $request
     * @return   array
     * @other    void
     */
    private function getClearRequestFile($request)
    {
        return collect($request->allFiles())->map(function ($val) {
            if (is_array($val)) {
                $res = collect($val)->map(function ($v) {
                    return $v->getClientOriginalName();
                });
            } else {
                $res = $val->getClientOriginalName();
            }
            return $res;
        })->toArray();
    }


    /**
     * @function 获取干净的请求头
     * @param \Illuminate\Http\Request $request
     * @return   array
     * @other    void
     */
    private function getClearRequestHeader($request)
    {
        return collect($request->header())->except(array_filter($this->setExceptHeader($request)))->map(function ($every_header, $key) {
            return (count($every_header) === 1) ? collect($every_header)->values()->first() : $every_header;
        })->toArray();
    }


    /**
     * @function 通过token获取user_id，这个有伪造的风险
     * @param \Illuminate\Http\Request $request
     * @return   int
     * @other    void
     */
    private function getIdWithToken($request)
    {
        $token = $request->header('authorization');
        if (!$token) {
            return 0;
        }

        $payload = (explode('.', $token)[1]) ?? null;
        if (is_null($payload)) {
            return 0;
        }

        $json = base64_decode($payload);
        $arr = json_decode($json, true);
        if (is_null($arr)) {
            return 0;
        }

        return $arr['sub'] ?? 0;
    }


    /**
     * @function 获取状态码
     * @param \Illuminate\Http\JsonResponse|\Illuminate\Http\Response $response
     * @return   string|array
     * @other    void
     */
    private function getHttpCode($response)
    {
        return $response->getStatusCode();
    }


    /**
     * @function 格式化响应数据
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Http\JsonResponse|\Illuminate\Http\Response $response
     * @return   string|array
     * @other    void
     */
    private function responseFormat($request, $response)
    {
        if ($response instanceof \Illuminate\Http\JsonResponse) {
            return collect($response->getData())->toArray();
        }

        if (!$this->isRecordNotJsonResponseData($request)) {
            return '非json';
        }

        if ($response instanceof \Illuminate\Http\Response) {
            return $response->getContent();
        }

        return '';
    }


    /**
     * @function 格式化数组并转换为字符串
     * @param    $request_and_response array
     * @return   string
     * @other    void
     */
    private function dataFormat($request_and_response)
    {
        $str = "\n";
        foreach ($request_and_response as $k => $v) {
            $k = str_pad($k, 9, ' ', STR_PAD_RIGHT);
            $v = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
            $str .= "{$k}: {$v}\n";
        }

        return $str;
    }


    /**
     * @function 获取程序占用的内存
     * @return   string
     * @other    void
     */
    private function getUsageMemory()
    {
        $bytes = memory_get_usage();
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $bytes /= pow(1024, ($i = floor(log($bytes, 1024))));
        return round($bytes, 2) . ' ' . $units[$i];
    }


    /**
     * @function 判断是否是xml
     * @param    $str string 要判断的xml数据
     * @return   bool
     */
    private function isXml($str)
    {
        libxml_use_internal_errors(true);
        simplexml_load_string($str);
        $errors = libxml_get_errors();
        libxml_clear_errors();
        return !$errors;
    }
}
